//
//  CarSelectView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/28/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit


protocol CarSelectViewProtocol {
    func onCarSelect (carModel: CarModel?)
    func didRemoveCar (indexPath: IndexPath)
    func createNewCar ()
    func hideCarSelectView()
}


final class CarSelectView: UIView {
    
    // MARK: - Outlets
    
    private lazy var headerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "cancel"), for: .normal)
        return btn
    }()
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
        lbl.textAlignment = .center
        lbl.textColor = .black
        lbl.sizeToFit()
        lbl.text = "Выберите авто"
        return lbl
    }()
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("Изменить", for: .normal)
        btn.setTitleColor(.blueColor, for: .normal)
        btn.titleLabel?.textAlignment = .right
        return btn
    }()
    private lazy var carsTable: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .white
        tableView.tableFooterView = UIView()
        tableView.register(CarSelectCell.self, forCellReuseIdentifier: "carCell")
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    private lazy var addCarView: UIView = {
        let view = UIView()
        
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        label.textColor = .blueColor
        label.textAlignment = .left
        label.text = "Добавить авто"
        
        let icon = UIImageView()
        icon.image = UIImage(named: "plus")
        icon.contentMode = .scaleAspectFit

        view.addSubview(label)
        view.addSubview(icon)
        
        label.snp.makeConstraints { (make) in
            make.leading.centerY.equalToSuperview()
        }
        icon.snp.makeConstraints { (make) in
            make.trailing.centerY.equalToSuperview()
            make.width.height.equalTo(22)
        }
        
        return view
    }()
    private lazy var addButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .blueColor
        btn.setTitle("Выбрать", for: .normal)
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 15
        return btn
    }()
    private lazy var emptyView: EmptyView = {
        let emptyView = EmptyView()
        emptyView.frame = CGRect(x: 0, y: 0, width: carsTable.frame.width, height: 200)
        return emptyView
    }()
    
    // MARK: - Properties
    
    private var cars: [CarModel]! = [] {
        didSet {
            if (cars.count == 0) {
                carsTable.tableHeaderView = emptyView
            } else {
                carsTable.tableHeaderView = nil
            }
            carsTable.reloadData()
        }
    }
    
    var delegate: CarSelectViewProtocol!
    
    // MARK: - UI Actions
    
    public func putCars (cars: [CarModel]) {
        self.cars = cars
    }
    public func addCars (cars: [CarModel]) {
        self.cars += cars
    }
    
    
    /// selecting car
    /// - Parameter indexPath: (Section, Row) data of Cell
    private func selectCarView (indexPath: IndexPath) {
        var output: [CarModel] = []
        for (i, car) in cars.enumerated() {
            var _car: CarModel = car
            if (i == indexPath.row) {
                _car.isSelected = !car.isSelected
            } else {
                _car.isSelected = false
            }
            output.append(_car)
        }
        self.cars = output
    }
    @objc private func readyBtnOnClick (sender: UIButton) {
        let carModel = cars.first {
            $0.isSelected
        }
        delegate.onCarSelect(carModel: carModel)
    }
    @objc private func editCells (sender: UIButton){
        carsTable.isEditing = !carsTable.isEditing
        sender.setTitle(carsTable.isEditing ? "Готово" : "Изменить", for: .normal)
    }
    @objc private func createNewCarClick (sender: UIButton) {
        delegate.createNewCar()
    }
    @objc private func hideView (sender: UIButton) {
        delegate.hideCarSelectView()
    }
    
    // MARK: - Init
    
    init () {
        super.init(frame: .zero)
        self.addViews()
        self.addConstraints()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - UI
    
    private func addViews () {
        self.backgroundColor = .white
        
        for view in [headerView, carsTable, addCarView, addButton] {
            self.addSubview(view)
        }
        headerView.addSubview(cancelBtn)
        headerView.addSubview(titleLbl)
        headerView.addSubview(deleteBtn)
        
        let gesture = UITapGestureRecognizer(target: self, action: #selector(createNewCarClick(sender:)))
        addCarView.addGestureRecognizer(gesture)
        
        
        cancelBtn.addTarget(self, action: #selector(hideView(sender:)), for: .touchUpInside)
        addButton.addTarget(self, action: #selector(readyBtnOnClick(sender:)), for: .touchUpInside)
        deleteBtn.addTarget(self, action: #selector(editCells(sender:)), for: .touchUpInside)
    }
    
    private func addConstraints () {
        headerView.snp.makeConstraints { (make) in
            make.height.equalTo(71)
            make.width.equalToSuperview()
            make.centerX.top.equalToSuperview()
        }
        cancelBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview().offset(24)
            make.width.equalTo(12)
            make.height.equalTo(20.5)
        }
        titleLbl.snp.makeConstraints { (make) in
            make.centerX.centerY.equalToSuperview()
        }
        deleteBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-24)
            make.width.equalTo(85)
            make.height.equalTo(22)
        }
        addButton.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().inset(20)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(44)
        }
        addCarView.snp.makeConstraints { (make) in
            make.bottom.equalTo(addButton.snp.top).offset(-12)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(60)
        }
        carsTable.snp.makeConstraints { (make) in
            make.top.equalTo(headerView.snp.bottom)
            make.bottom.equalTo(addCarView.snp.top)
            make.leading.trailing.equalToSuperview()
        }
    }
}


extension CarSelectView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cars.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "carCell") as! CarSelectCell
        cell.carModel = cars[indexPath.row]
        cell.delegate = self
        cell.indexPath = indexPath
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectCarView(indexPath: indexPath)
    }

    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let contextItem = UIContextualAction(style: .destructive, title: "Удалить") {  (contextualAction, view, boolValue) in
            self.delegate.didRemoveCar(indexPath: indexPath)
        }
        
        let swipeActions = UISwipeActionsConfiguration(actions: [contextItem])
        return swipeActions
    }
}

extension CarSelectView: CarSelectProtocol {
    func didSelectCar(indexPath: IndexPath) {
        self.selectCarView(indexPath: indexPath)
    }
}
